package com.ruoyi.scheduler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import com.ruoyi.domain.MaterielOne;
import com.ruoyi.domain.MaterielThree;
import com.ruoyi.mapper.MaterielOneMapper;
import com.ruoyi.utils.CustomSnakeCaseToCamelCaseStrategy;
import com.ruoyi.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.thymeleaf.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class MaterielOneSchedulerService {

    @Autowired
    MaterielOneMapper materielOneMapper;

    @Value("${scheduler.enabled:true}")
    private boolean schedulerEnabled;
    /**
     * 每天10点执行
     */

    public String getMaterielOne() {
        String url = "http://192.168.3.35:9990/CROSS/RESTful"; // 第三方API的URL

        // 请求头信息
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("digi-key", "4194DA59D787CDDD159746D65E5CCB11");
        headers.put("digi-host", "{\"ver\":\"5.7\",\"prod\":\"YMES\",\"timezone\":\"+8\",\"ip\":\"192.168.3.35\",\"id\":\"\",\"lang\":\"zh_CN\",\"acct\":\"dcms\",\"timestamp\":\"2018071990007275\"}");
        headers.put("digi-service", "{\"prod\":\"E10\",\"ip\":\"192.168.3.35\",\"name\":\"ymes.issue_receipt.query\",\"id\":\"DemoCompany_External\"}");
        headers.put("digi-data-exchange-protocol", "1.0");
        headers.put("digi-type", "sync");

        //请求体信息
        String requestBody = "\t{\t\n" +
                "\t  \"std_data\": {\t\n" +
                "\t    \"parameter\": {\t\n" +
                "\t      \"pageSize\": 5000,\t\n" +
                "\t      \"pageNo\": 1,\t\n" +
                "\t      \"isGetSchema\": false,\t\n" +
                "\t      \"isGetCount\": false,\t\n" +
                "\t      \"conditions\": [],\t\n" +
                "\t      \"orders\": []\t\n" +
                "\t    }\t\n" +
                "\t  }\t\n" +
                "\t}\t\n";
        String response = null;
        try {
            // 调用Get请求
            //String response = HttpUtils.sendGet(url, headers);


            // 调用Post请求
            response = HttpUtils.sendPost(url, headers, requestBody);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }


    public List<MaterielOne> listMaterielOne() throws JsonProcessingException {
        //处理接口数据
        String jsonOne = StringUtils.substringAfter(getMaterielOne(), "[");
        String jsonTwo = StringUtils.substringBefore(jsonOne, "]");
        String jsonStr = "["+jsonTwo+"]";
        ObjectMapper mapper = new ObjectMapper();

        mapper.setPropertyNamingStrategy(new CustomSnakeCaseToCamelCaseStrategy());

        List<MaterielOne> materielOnes = mapper.readValue(jsonStr, new TypeReference<List<MaterielOne>>() {});

        for (MaterielOne materielOne:materielOnes){
            if(materielOne.getDocDate() != null && !materielOne.getDocDate().isEmpty()){
                materielOne.setDocDate(materielOne.getDocDate().substring(0,10));
            }
            if(materielOne.getCreateDate() != null && !materielOne.getCreateDate().isEmpty()){
                materielOne.setCreateDate(materielOne.getCreateDate().substring(0,10));
            }
            if(materielOne.getLastModifiedDate() != null && !materielOne.getLastModifiedDate().isEmpty()){
                materielOne.setLastModifiedDate(materielOne.getLastModifiedDate().substring(0,10));
            }

        }
        return materielOnes;
    }

    //@Scheduled(fixedRate = 60000) // 每分钟执行一次
    @Scheduled(fixedRate = 3600000) // 每小时执行一次
    //@Scheduled(fixedRate = 86400000) // 每天执行一次
    @Transactional
    public void scheduleTask(){
        // 判断是否启用定时任务
        if (!schedulerEnabled || java.lang.management.ManagementFactory.getRuntimeMXBean().getInputArguments().toString().contains("jdwp")) {
            return;
        }

        try {
            List<MaterielOne> materielOneList1= materielOneMapper.selectAll();//数据库中查所有
            List<MaterielOne> materielOneList2 = listMaterielOne();//接口中拿到的数据
            List<MaterielOne> list =  uniqueListOne(materielOneList2, materielOneList1);///接口中除去数据库中重复的数据
            for(MaterielOne materielOne:list){
                materielOneMapper.insertMaterielOne(materielOne);//一条条添加到数据库中
            }
        } catch (JsonProcessingException e) {
            // 记录日志或处理异常
            e.printStackTrace();
        } catch (Exception e) {
            // 处理其他可能的异常
            e.printStackTrace();
        }
    }


    // 自定义去重过滤器
    private List<MaterielOne> uniqueListOne(List<MaterielOne> source, List<MaterielOne> target) {
        if(CollectionUtils.isEmpty(source)){
            return List.of();
        }
        if(CollectionUtils.isEmpty(target)){
            return source;
        }
        return source.stream()
                .filter(sc -> target.stream().noneMatch(ta ->
                    sc != null && ta != null  &&
                  /*  Objects.equals(sc.getDocDate(), ta.getDocDate()) &&
                    Objects.equals(sc.getDocFullName(), ta.getDocFullName()) &&
                    Objects.equals(sc.getDocNo(), ta.getDocNo()) &&
                    Objects.equals(sc.getItemCode(), ta.getItemCode()) &&
                    Objects.equals(sc.getItemDescription(), ta.getItemDescription()) &&
                    Objects.equals(sc.getItemSpecification(), ta.getItemSpecification()) &&
                    Objects.equals(sc.getIssueReceiptQty(), ta.getIssueReceiptQty()) &&
                    Objects.equals(sc.getActualIssueReceiptQty(), ta.getActualIssueReceiptQty()) &&
                    Objects.equals(sc.getLotCode(), ta.getLotCode()) &&
                    Objects.equals(sc.getIssueComment(), ta.getIssueComment()) &&
                    Objects.equals(sc.getBinCode(), ta.getBinCode()) &&
                    Objects.equals(sc.getBinName(), ta.getBinName()) &&
                    Objects.equals(sc.getItemDescription1(),ta.getItemDescription1()) &&
                    Objects.equals(sc.getItemCode1(),ta.getItemCode1()) &&
                    Objects.equals(sc.getItemSpecification1(),ta.getItemSpecification1()) &&
                    Objects.equals(sc.getLotCode1(),ta.getLotCode1()) &&
                    Objects.equals(sc.getLotDescription(),ta.getLotDescription()) &&
                    Objects.equals(sc.getRequiredQty(),ta.getRequiredQty()) &&
                    Objects.equals(sc.getRequIncludeMultQty(),ta.getRequIncludeMultQty()) &&
                    Objects.equals(sc.getLeastRequiredQty(),ta.getLeastRequiredQty()) &&
                    Objects.equals(sc.getIssuedQty(),ta.getIssuedQty()) &&
                    Objects.equals(sc.getWarehouseCode(),ta.getWarehouseCode()) &&
                    Objects.equals(sc.getWarehouseName(),ta.getWarehouseName()) &&
                    Objects.equals(sc.getCreateDate(),ta.getCreateDate()) &&
                    Objects.equals(sc.getUserName1(),ta.getUserName1()) &&
                    Objects.equals(sc.getUserName(),ta.getUserName()) &&
                    Objects.equals(sc.getLastModifiedDate(),ta.getLastModifiedDate()) &&
                    Objects.equals(sc.getApproveStatus(),ta.getApproveStatus()) &&
                    Objects.equals(sc.getEmployeeName1(),ta.getEmployeeName1())*/
                            Objects.equals(sc.getDocDate(), ta.getDocDate()) &&
                            Objects.equals(sc.getDocNo(), ta.getDocNo()) &&
                            Objects.equals(sc.getItemCode(), ta.getItemCode()) &&
                            Objects.equals(sc.getLotCode(), ta.getLotCode()) &&
                            Objects.equals(sc.getItemCode1(),ta.getItemCode1()) &&
                            Objects.equals(sc.getLotCode1(),ta.getLotCode1())


                ))
                .collect(Collectors.toList());
    }


}
